package com.backend.demo1.services;

import com.backend.demo1.config.ApiException;
import com.backend.demo1.mapper.RoleMapper;
import com.backend.demo1.mapper.UserMapper;
import com.backend.demo1.models.Role;
import com.backend.demo1.models.User;
import com.backend.demo1.utils.JwtUtil;
import com.backend.demo1.utils.PasswordUtil;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class AuthService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private PasswordUtil passwordUtil;

    @Autowired
    private RoleMapper roleMapper;

    public String register(User user) {
        User existingUser = userMapper.findByUsername(user.getUsername());
        if (existingUser != null) {
            throw new ApiException(409, "用户名已存在");
        }

        String hashPwd = passwordUtil.hashPassword(user.getPassword());

        // 处理 Role 对象
        Role role = user.getRole();
        if (role != null && role.getName() != null) {
            Role existingRole = roleMapper.findByName(role.getName());
            if (existingRole == null) {
                throw new ApiException(400, "角色不存在");
            }
            user.setRole(existingRole);
        } else {
            throw new ApiException(400, "角色信息不能为空");
        }

        user.setPassword(hashPwd);
        userMapper.insertUser(user);

        return jwtUtil.generateToken(user.getUsername());
    }


    public Map<String, Object> login(User input) {
        // 查询用户及其角色名称
        Map<String, Object> userWithRole = userMapper.findUserWithRoleName(input.getUsername());
        if (userWithRole == null || userWithRole.get("username") == null) {
            throw new ApiException(401, "用户名错误");
        }

        // 校验密码
        String storedPassword = (String) userWithRole.get("password");
        if (!passwordUtil.checkPassword(input.getPassword(), storedPassword)) {
            throw new ApiException(401, "密码错误");
        }

        // 生成 JWT Token
        String token = jwtUtil.generateToken((String) userWithRole.get("username"));

        // 构造返回结果
        Map<String, Object> response = new HashMap<>();
        response.put("token", token);
        response.put("role", userWithRole.get("roleName"));

        return response;
    }

    // 示例方法，使用 findUserIdByUsername
    public Long findUserIdByUsername(String username) {
        Long userId = userMapper.findUserIdByUsername(username);
        if (userId == null) {
            throw new ApiException(404, "用户不存在");
        }
        return userId;
    }

    
}